package com.kyzh.core.pager.login

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.AdapterView
import androidx.core.content.ContextCompat
import com.bytedance.applog.game.GameReportHelper
import com.gushenge.atools.util.getStatusBarHeight
import com.gushenge.atools.util.setMargins
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.PhoneCodeBean
import com.gushenge.core.dao.GlobalConsts
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.impls.UserImpl
import com.gushenge.core.requests.AppRequest
import com.gushenge.core.requests.UserRequest
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.R
import com.kyzh.core.adapters.PhoneCodeAdapter
import com.kyzh.core.utils.*
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import io.github.armcha.autolink.MODE_URL
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_phonelogin.*
import kotlinx.android.synthetic.main.activity_phonelogin.btLogin
import kotlinx.android.synthetic.main.activity_phonelogin.etPassword
import kotlinx.android.synthetic.main.activity_phonelogin.ivDel
import kotlinx.android.synthetic.main.activity_phonelogin.ivLogo
import kotlinx.android.synthetic.main.activity_phonelogin.ivShowpass
import kotlinx.android.synthetic.main.activity_phonelogin.tvPact
import kotlinx.android.synthetic.main.activity_phonelogin.tvQQLogin
import kotlinx.android.synthetic.main.activity_phonelogin.tvRegister
import kotlinx.android.synthetic.main.activity_phonelogin.tvWxLogin
import kotlinx.coroutines.*
import com.gushenge.core.toast
import com.kyzh.core.activities.BrowserActivity
import com.kyzh.core.activities.PasswordActivity

class PhoneLoginActivity : BaseActivity() {
    private var job:Job?=null
    private var sessionId = ""
    private var isRegister = false
    private var phoneCode = "+86"
    private lateinit var  beans: ArrayList<PhoneCodeBean>
    var loginbox = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_phonelogin)
        initUI()
        cbloginphone.isChecked= loginbox
        cbloginphone.setOnCheckedChangeListener { buttonView, isChecked ->
            loginbox =isChecked
        }
    }


    private fun initUI() {
        if(MMKVConsts.languageConfig.isNullOrEmpty()||MMKVConsts.languageConfig=="[]"){
            spPhoneCode.visibility=View.GONE
        }else{
            spPhoneCode.visibility=View.VISIBLE
        }
        AppRequest.getPhoneCode {
            beans = this
            val spTypeAdapter = PhoneCodeAdapter(this@PhoneLoginActivity, R.layout.item_spinner_code,this)
            spPhoneCode.setPopupBackgroundDrawable(ContextCompat.getDrawable(this@PhoneLoginActivity,R.drawable.bg_6dp_white))
            spPhoneCode.adapter = spTypeAdapter
            spPhoneCode.dropDownWidth=dip(300)
            spPhoneCode.onItemSelectedListener = object :AdapterView.OnItemSelectedListener{
                override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                    phoneCode = this@getPhoneCode[p2].code
                }

                override fun onNothingSelected(p0: AdapterView<*>?) {
                }

            }
        }
        tvQQLogin.setVisibility(MMKVConsts.qqLogin)
        tvWxLogin.setVisibility(MMKVConsts.wxLogin)
        ivLogo.setMargins(0,
                if (isNotLongScreenDevice()){
                    dip(58)
                }else{
                    dip(88)+getStatusBarHeight()
                },
                0,
                0
        )
        btLogin.setOnClickListener {
            if(!loginbox){
                getString(R.string.pleasecheck).toast()
                return@setOnClickListener
            }
            val name = etPhone.text.toString().trim()
            val pass = etPassword.text.toString().trim()
            val code = etCode.text.toString().trim()
            val share = etShare.text.toString().trim()
            UserRequest.register(name,phoneCode,isRegister,pass,sessionId,code,share){
                GameReportHelper.onEventRegister("phone",true);
                imLogin()
                LiveEventBus.get<Boolean>("login").post(true)
                finish()
            }
        }
        tvPact.addAutoLinkMode(
                MODE_URL
        )
        tvPact.addUrlTransformations(
                GlobalConsts.REGISTER_PACT to "“${getString(R.string.registerAgreement)}”",
                GlobalConsts.PRIVACY_PACT to "“${getString(R.string.privacyPolicy)}”"
        )
        tvPact.urlModeColor = ContextCompat.getColor(this, R.color.colorPrimary)
        tvPact.text = String.format(getString(R.string.loginPrivacy),GlobalConsts.REGISTER_PACT,GlobalConsts.PRIVACY_PACT)

        tvPact.onAutoLinkClick {
            startActivity<BrowserActivity>(GlobalKeys.TITLE to it.transformedText.substring(1,it.transformedText.length-1), GlobalKeys.LINK to it.originalText)
        }
        tvRegister.setOnClickListener{
            startActivity<RegisterActivity>()
            finish()
        }
        tvAccountLogin.setOnClickListener{
            startActivity<LoginActivity>()
            finish()
        }
        ivShowpass.setOnClickListener{
            showPass()
        }
        ivDel.setOnClickListener {
            etPhone.setText("")
        }
        tvQQLogin.setOnClickListener{
            if(!loginbox){
                getString(R.string.pleasecheck).toast()
                return@setOnClickListener
            }
            UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.QQ, authListener)
        }
        tvWxLogin.setOnClickListener{
            if(!loginbox){
                getString(R.string.pleasecheck).toast()
                return@setOnClickListener
            }
            UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, authListener)
        }
        tvGetCode.setOnClickListener {
            (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(tvGetCode.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
            UserRequest.getCodeByPhoneLogin(etPhone.text.toString(),phoneCode){
                startTimer()
                isRegister = reg==0
                group.visibility = if (isRegister) View.VISIBLE else View.GONE
                sessionId = sessionid
            }
        }
    }
    /*tvFindPassword -> startActivity<BaseFragmentActivity>(GlobalKeys.TYPE to BaseFragmentActivity.RETRIEVE_PASSWORD)*/

    // 设置密码  type ==1  QQ   2 wx
    fun setPassword(token: String? ,type :Int){
        PasswordActivity.start(this, token, type)
    }
    private fun showPass() {
        if (etPassword.transformationMethod != HideReturnsTransformationMethod.getInstance()) {
            etPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
            ivShowpass.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_login_showpassword))
        } else {
            etPassword.transformationMethod = PasswordTransformationMethod.getInstance()
            ivShowpass.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_login_hidepassword))
        }
    }

    var authListener: UMAuthListener = object : UMAuthListener {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        override fun onStart(platform: SHARE_MEDIA) {}
        override fun onComplete(platform: SHARE_MEDIA, action: Int, data: Map<String, String>) {
            if (platform == SHARE_MEDIA.QQ) {
                UserImpl.checkReg(data["accessToken"].toString() ){
                    val code1 = this
                    if(code1.code == 1){
                        UserImpl.loginByQqWx(data["accessToken"] ?: "", "1",null,null) {
                            if(code == 1){
                                MMKVConsts.uid= this.data.toString()
                                imLogin()
                                LiveEventBus.get<Boolean>("login").post(true)
                                finish()
                            }else{
                                message.toast()
                            }
                        }
                    }else{
                        GameReportHelper.onEventRegister("qq",true);

                        setPassword(data["accessToken"] ?: "",1)
                    }
                }
            } else {
                UserImpl.checkReg(data["uid"].toString() ){
                    val code1 = this
                    if(code1.code == 1){
                        UserImpl.loginByQqWx(data["uid"] ?: "", "2",null,null) {
                            if(code == 1){
                                MMKVConsts.uid= this.data.toString()
                                imLogin()
                                LiveEventBus.get<Boolean>("login").post(true)
                                finish()
                            }else{
                                message.toast()
                            }
                        }
                    }else{
                        GameReportHelper.onEventRegister("wx",true);

                        setPassword(data["uid"] ?: "",2)
                    }
                }
            }
        }

        override fun onError(platform: SHARE_MEDIA, action: Int, t: Throwable) {}

        override fun onCancel(platform: SHARE_MEDIA, action: Int) { getString(R.string.cancelLogin).toast() }
    }
    //Im登录
    private fun imLogin(){
//        if(MMKVConsts.imOpen) {
//            LiveRequest.geiLiveUserUid {
//                this?.apply {
//                    TUILogin.login(live_uid, live_sign, object : V2TIMCallback {
//                        override fun onSuccess() {
//                            Log.e(TUIUtils.TAG, "onSuccess")
//                        }
//
//                        override fun onError(p0: Int, p1: String?) {
//                            Log.e(TUIUtils.TAG, "onError: $p0  $p1")
//                        }
//                    })
//                }
//            }
//        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == 1000){
            if(resultCode == RESULT_OK){
                finish()
            }
        }else{

            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
        }

    }

    fun startTimer(){
        job = GlobalScope.launch {
            repeat(60){ t ->
                val spec = 59-t
                handler.sendMessage(Message().also {
                    it.what = 0
                    it.arg1 = spec
                })
                delay(1000)
            }
            cancel()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        job?.cancel()
    }

    @SuppressLint("HandlerLeak")
    private val handler =object : Handler() {
        override fun handleMessage(msg: Message) {
            when(msg.what){
                0-> {
                    if (msg.arg1==0){
                        tvGetCode.text = getString(R.string.getVerifyCode)
                        tvGetCode.setTextColor(ContextCompat.getColor(this@PhoneLoginActivity,R.color.colorPrimary))
                        tvGetCode.isClickable = true
                        etPhone.enableEdit()
                        ivDel.visibility = View.VISIBLE
                    }else{
                        tvGetCode.text = "${msg.arg1}S"
                        tvGetCode.setTextColor(Color.parseColor("#cccccc"))
                        tvGetCode.isClickable = false
                        etPhone.disableEdit()
                        ivDel.visibility = View.GONE
                    }
                }
            }
        }
    }

}
